package com.mhr.controller;

import com.mhr.pojo.Student;
import com.mhr.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @Author manster
 * @Date 2021/5/26
 **/
@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    //获取所有学生信息
    @GetMapping("/list")
    public String list(Model model){
        List<Student> students = studentService.listStudent();

        model.addAttribute("students", students);
        return "liststudent";
    }

    @PostMapping("/search")
    public String list(@RequestParam(value = "name", required = false) String name, Model model){
        List<Student> students;
        if(StringUtils.hasText(name)){
            students = studentService.getStudentByName(name);
        } else {
            students = studentService.listStudent();
        }
        model.addAttribute("students", students);
        return "liststudent";
    }

    //删除学生
    @GetMapping("/delete")
    public String delete(@RequestParam("id") Integer id, Model model){
        int i = studentService.deleteStudent(id);
        if (i>0){
            model.addAttribute("msg", "删除成功");
        } else {
            model.addAttribute("msg", "删除失败");
        }
        return "redirect:/list";
    }

    //新增跳转
    @GetMapping("/add")
    public String add(Model model){
        model.addAttribute("student", new Student());
        return "editstudent";
    }

    //修改跳转
    @GetMapping("/update")
    public String update(@RequestParam("id") Integer id, Model model){
        model.addAttribute("student", studentService.getStudentById(id));
        return "editstudent";
    }

    @PostMapping("/save")
    public String save(Student student, Model model){
        Student res = studentService.getStudentById(student.getId());
        //该学生存在则为修改操作
        if(res != null){
            int i = studentService.updateStudent(student);
            if (i>0){
                model.addAttribute("msg", "修改成功");
            } else {
                model.addAttribute("msg", "修改失败");
            }
            return "redirect:/list";
        }else{
        //否则为新增操作
            int i = studentService.insertStudent(student);
            if (i>0){
                model.addAttribute("msg", "新增成功");
            } else {
                model.addAttribute("msg", "新增失败");
            }
            return "redirect:/list";
        }

    }

}
